﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Contract.MVC;
using Way.Bus.WMS.Model;
using Way.EAP.DataAccess.Entity;
using Way.EAP.DataAccess.Data;
using System.Data;
using Way.Bus.Model;
using Way.Contract.Data;
using Way.Contract.Data.ControllerData;
using Way.Contract;
using Way.Bus.Wms.Model;
using Way.EAP.DataAccess.Regulation;

namespace Way.Bus.WMS.ST.Controllers.InOrder
{
    public class ReceiveOrderController : Way.Bus.WMS.Controllers.StockInOrderController
    {
        public ReceiveOrderController() : base(new Way.Bus.WMS.Model.StockInOrder()) { }

        #region 重写方法
        //是否启用审核
        public override bool IsReviewedState
        {
            get
            {
                return false;
            }
        }
        protected override string OnGetControllerDescription()
        {
            return "入库单";
        }

        protected override string OnGetPath()
        {
            return "Views/ST/ReceiveOrder.htm";
        }
 

        /// <summary>
        /// 外键查询初始化界面显示
        /// </summary>
        /// <param name="model"></param>
        /// <param name="data"></param>
        protected override void OnForeignIniting(IModel model, InitData data)
        {
            base.OnForeignIniting(model, data);
            //选择商品
            if (this.fdata.filedname == "MATERIALCODE")
            {
                if (this.ActionItem != null && this.ActionItem["SOURCEID"] != null && this.ActionItem["SOURCEID"].ToString() != "")
                {
                    IModel md = new StockInNoticeMaterials();
                    data.modeldata = md.GetModelData();

                    foreach (ItemData d in data.modeldata.childitem)
                    {
                        ReceiveNoticeController.InitInNoticeMaterials(data.modeldata, d);
                    }
                }
                else
                {
                    foreach (ItemData d in data.modeldata.childitem)
                    {
                        ReceiveNoticeController.InitMaterials(data.modeldata, d);
                    }
                }
            }
            //选择货位
            if (this.fdata.filedname == "DEPOTWBS")
            {
                if (this.ActionItem != null && this.ActionItem["SOURCEID"] != null && this.ActionItem["SOURCEID"].ToString() != "")
                {
                    foreach (ItemData d in data.modeldata.childitem)
                    {
                        ReceiveOrderController.InitWareHouse(data.modeldata, d);
                    }
                }
            }
        }

        protected override ReadTable OnForeignLoad(IModel model, loadItem item)
        {
            //选择商品
            if (this.fdata.filedname == "MATERIALCODE")
            {
                if (this.ActionItem["SOURCEID"] != null && this.ActionItem["SOURCEID"].ToString() != "")
                {
                    StockInNoticeMaterials oom = new StockInNoticeMaterials();
                    if (oom != null)
                    {
                        string strSQL = "";
                        foreach (SQLWhere sw in item.whereList)
                        {
                            if (sw.ColumnName.EndsWith("MCODE"))
                            {
                                sw.ColumnName = "MCODE";
                            }
                            if (sw.ColumnName.EndsWith("CODE"))
                            {
                                sw.ColumnName = "MCODE";
                            }
                            if (sw.ColumnName.EndsWith("MATERIALCODE"))
                            {
                                sw.ColumnName = "MATERIALCODE";
                            }
                            if (sw.ColumnName.EndsWith("FNAME"))
                            {
                                sw.ColumnName = "f2";
                            }
                            if (sw.ColumnName.EndsWith("FMODEL"))
                            {
                                sw.ColumnName = "FMODEL";
                            }
                            if (sw.ColumnName.EndsWith("NUM"))
                            {
                                sw.ColumnName = "NUM";
                            }
                            if (sw.ColumnName.EndsWith("STAYNUM"))
                            {
                                sw.ColumnName = "STAYNUM";
                            }
                            if (sw.ColumnName.EndsWith("FINISHNUM"))
                            {
                                sw.ColumnName = "FINISHNUM";
                            }
                            if (sw.ColumnName.EndsWith("IsDisable"))
                            {
                                sw.ColumnName = "IsDisable";
                            }
                            strSQL += " and " + sw.where();
                        }
                        item.rowsql = ((IEntityBase)oom).GetSearchSQL() + " where parentid=" + this.ActionItem["SOURCEID"].ToString() + strSQL;
                    }
                }
                else
                    item.rowsql = Common.GetNoticeMaterialsSQL(item.rowsql, "");
            }

            //选择货位
            if (this.fdata.filedname == "DEPOTWBS")
            {
                int wid, mid, kid, lid = 0;
                if (this.ActionItem["TOWHNO"] != null && !string.IsNullOrEmpty(this.ActionItem["TOWHNO"].ToString()))
                    wid = int.Parse(this.ActionItem["TOWHNO"].ToString());
                else
                    throw new Exception("异常：请先选择仓库！");
                if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                    kid = int.Parse(this.ActionItem["CLIENTNO"].ToString());
                else
                    throw new Exception("异常：请先选择客户！");
                StockInOrderMaterials mm = EntityHelper.ToEntity(this.fdata.eventrow, typeof(StockInOrderMaterials)) as StockInOrderMaterials;
                if (mm != null && mm["MATERIALCODE"] != null && !string.IsNullOrEmpty(mm["MATERIALCODE"].ToString()))
                {
                    mid = int.Parse(mm["MATERIALCODE"].ToString());
                    lid = mm.GetForeignObject<BusinessCommodity>(this.model.GetDataAction()).ClassID;
                }
                else
                {
                    throw new Exception("异常：请先选择货物名称！");
                }
                string strSQL = "";
                foreach (SQLWhere sw in item.whereList)
                {
                    if (sw.ColumnName.EndsWith("WAREHOUSENAME"))
                    {
                        sw.ColumnName = "t3.WAREHOUSENAME";
                    }
                    if (sw.ColumnName.EndsWith("CODE"))
                    {
                        sw.ColumnName = "t2.CODE";
                    }
                    if (sw.ColumnName.EndsWith("IsDisable"))
                    {
                        sw.ColumnName = "t2.IsDisable";
                    }
                    if (sw.ColumnName.EndsWith("ID"))
                    {
                        sw.ColumnName = "t4.ID";
                    }
                    strSQL += " and " + sw.where();
                }
                item.rowsql = DepotwbsManage.GetDepotHWOrderByIdSQL(lid, wid, kid, strSQL); 
                item.sort = "SID";
                item.sort = "ID";
                item.sort = "HQID";
                //item.rowsql = DepotwbsManage.GetDepotHWSQL(lid, wid, kid);

            }

            //设置客户选择框只能选择客户类型的用户信息
            if (this.fdata.filedname == "CLIENTNO")
            {
                item.rowsql = "select * from (" + item.rowsql + ") t where t.ftype = '2'";
            }
            //设置仓库选择框只能选择仓库信息
            if (this.fdata.filedname == "TOWHNO")
            {
                item.rowsql = "select * from (" + item.rowsql + ") t where t.WHTYPE = '0'";
            }
            //设置入库员选择框只能选择库管类型的用户信息
            if (this.fdata.filedname == "WORKERID" || this.fdata.filedname == "SUBMITEDBY")
            {
                item.rowsql = "select t.* from (" + item.rowsql + ") t LEFT JOIN Acc_Bus_UserRole t1 on t.[ID]=t1.[UserID] WHERE t1.RoleID = '4'";
            }
            if (this.fdata.filedname == "PARENTID" && this.fdata.objectname.EndsWith("StockInNoticeMaterials"))
            {
                item.rowsql = Common.GetMaterialsBatchSQL(item.rowsql);
            } if (this.fdata.filedname == "PARENTID" && this.fdata.objectname.EndsWith("StockInOrderMaterials"))
            {
                item.rowsql = Common.GetMaterialsBatchSQL(item.rowsql);
            }
            return base.OnForeignLoad(model, item);
        }

        protected override void OnForeignLoaded(IModel model, ReadTable table)
        {
            if (this.fdata.filedname == "MATERIALCODE")
            {
                if (this.ActionItem["SOURCEID"] != null && this.ActionItem["SOURCEID"].ToString() != "")
                {
                    StockInNoticeMaterials oom = new StockInNoticeMaterials();
                    string fname = oom.GetAppendPropertyKey("MATERIALCODE");
                    table.rows.Columns.Add("FNAME");
                    table.rows.Columns.Add("CODE");
                    foreach (DataRow r in table.rows.Rows)
                    {
                        r["ID"] = r["MATERIALCODE"];
                        r["FNAME"] = r[fname];
                        r["CODE"] = r["MCODE"];
                    }
                }
            }
            //选择货位
            if (this.fdata.filedname == "DEPOTWBS")
            {
                if (this.ActionItem["SOURCEID"] != null && this.ActionItem["SOURCEID"].ToString() != "")
                {

                    //int wid, mid, kid, lid = 0;
                    //if (this.ActionItem["TOWHNO"] != null && !string.IsNullOrEmpty(this.ActionItem["TOWHNO"].ToString()))
                    //    wid = int.Parse(this.ActionItem["TOWHNO"].ToString());
                    //else
                    //    throw new Exception("异常：请先选择仓库！");
                    //if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                    //    kid = int.Parse(this.ActionItem["CLIENTNO"].ToString());
                    //else
                    //    throw new Exception("异常：请先选择客户！");
                    //StockInOrderMaterials mm = EntityHelper.ToEntity(this.fdata.eventrow, typeof(StockInOrderMaterials)) as StockInOrderMaterials;
                    //if (mm != null && mm["MATERIALCODE"] != null && !string.IsNullOrEmpty(mm["MATERIALCODE"].ToString()))
                    //{
                    //    mid = int.Parse(mm["MATERIALCODE"].ToString());
                    //    lid = mm.GetForeignObject<BusinessCommodity>(this.model.GetDataAction()).ClassID;
                    //}
                    //else
                    //{
                    //    throw new Exception("异常：请先选择货物名称！");
                    //}
                    //IDataAction action = this.model.GetDataAction();
                    //string sql = DepotwbsManage.GetDepotHWOrderByIdSQL(lid, wid, kid);
                    //DataTable dataTable = action.GetDataTable(sql);
                    //table.total = dataTable.Rows.Count;
                    //table.rows = dataTable;


                    //if (table.rows.Rows.Count == 0)
                    //{
                    //IDataAction action = this.model.GetDataAction();
                    //string sql = "select RANK() over(order by id asc) ROWINDEX,"
                    //    + " t.ID,t.CODE,t.WHTYPE,t.WAREHOUSENAME,t.STATUS"
                    //    + " from Acc_WMS_WareHouse t"
                    //    + " where t.WHTYPE = '2' and t.STATUS = '0'";

                    //DataTable dataTable = action.GetDataTable(sql);
                    //table.total = dataTable.Rows.Count;
                    //table.rows = dataTable;
                    //}
                    
                    foreach (DataRow r in table.rows.Rows)
                    {
                        //r["CODE"] = r["HQName"];
                        //r["DEPOTWBS"] = r["WAREHOUSENAME"];
                        r["CODE"] = r["CODE"];
                        r["WAREHOUSENAME"] = r["HQName"];
                    }
                    
                }
            }
            base.OnForeignLoaded(model, table);
        }

        protected override ActionCommand[] OnInitCommand(ActionCommand[] commands)
        {
            //获取所有按钮集合
            foreach (ActionCommand ac in commands)
            {
                //隐藏取消提交按钮
                if (ac.command == "UnSubmitData")
                {
                    ac.visible = false;
                }
            }
            return base.OnInitCommand(commands);
        }

        /// <summary>
        /// 初始化显示与否
        /// </summary>
        /// <param name="data"></param>
        /// <param name="item"></param>
        protected override void OnInitViewChildItem(ModelData data, ItemData item)
        {
            if (item.IsField("rowindex"))
            {
                item.isedit = false;
            }

            InitInOrder(data, item);
            InitInOrderMaterials(data, item);
            InitInNoticeMaterials(data, item);
            InitInSequence(data, item);

            //关闭多余的叶签
            if (data.name.EndsWith("StockInNoticeMaterials1"))
            {
                data.visible = false;
            }
            if (data.name.EndsWith("LogData"))
            {
                data.visible = false;
            }
            if (data.name.EndsWith("Sequence"))
            {
                data.visible = true;
                if (item.IsField("SEQUENCECODE"))
                    item.visible = true;
                else
                    item.visible = false;
            }
        }

        public static void InitInOrder(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockInOrder"))
            {
                //修改弹出窗口的title
                data.title = "入库单";
                //设置字段不能为空
                if (item.IsField("SourceOutCode")
                    || item.IsField("TOWHNO")
                    || item.IsField("WORKERID"))
                {
                    item.required = true;
                }
                //隐藏属性信息
                if (item.IsField("OfficeWorker")
                      || item.IsField("STOCKTYPE")
                      || item.IsField("IsDisable")
                      || item.IsField("SourceName")
                      || item.IsField("Reviewedby")
                      || item.IsField("Revieweddate")
                      || item.IsField("WORKERID")
                      || item.IsField("BUMEN")
                      || item.IsField("IsReviewed")
                      || item.IsField("INOUTTIME")
                      || item.IsField("RowIndex")
                )
                    item.visible = false;
                if (item.IsField("CLIENTNO"))
                    item.title = "客户";
                if (item.IsField("SourceCode"))
                    item.disabled = true;
                //if (item.IsField("WORKERID"))
                //{
                //    item.title = "库管员";
                //    if (item.foreign != null)
                //    {
                //        item.foreign.rowdisplay.Add(("OrganizationID").ToUpper(), "BUMEN");//key是联系人表字段，value是客户表字段
                //    }
                //}
                //设置不可写
                if (item.IsField("CODE"))
                {
                    item.disabled = true;
                    item.title = "单号";
                }
                if (item.IsField("STATE"))
                {
                    item.disabled = true;
                }
                //设置顺序
                if (item.field == "REMARK")
                    item.index = 4;

            }
        }

        public static void InitInOrderMaterials(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockInOrderMaterials"))
            {
                data.title = "入库单明细";
                if (item.IsField("PARENTID")
                     || item.IsField("SourceCode")
                     || item.IsField("STATE")
                    //|| item.IsField("BATCHNO")
                     || item.IsField("BUMEN")
                     || item.IsField("WORKERID")
                     || item.IsField("IsDisable")
                     || item.IsField("code")
                     || item.IsField("Createdby")
                     || item.IsField("Creationdate")
                     || item.IsField("Reviewedby")
                     || item.IsField("Revieweddate")
                    || item.IsField("Submitedby")
                     || item.IsField("IsReviewed")
                     || item.IsField("IsSubmited")
                    || item.IsField("Submiteddate")
                    //|| item.IsField("SENBATCHNO")
                     || item.IsField("PORTNAME")
                    )
                    item.visible = false;
                if (item.IsField("SENBATCHNO"))
                    item.title = "有效期";
                if (item.IsField("FINISHNUM") || item.IsField("STAYNUM"))
                {
                    item.disabled = true;
                    item.visible = false;
                }

                if (item.IsField("MATERIALCODE"))
                {
                    item.title = "货物名称";
                    if (item.foreign != null)
                    {
                        //item.foreign.rowdisplay.Add("FMOBILE", "FMOBILE");//key是联系人表字段，value是客户表字段
                        item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                        item.foreign.rowdisplay.Add("CODE", "MCODE");
                        item.foreign.rowdisplay.Add("BATCHNO", "BATCHNO");
                    }
                }
                if (item.IsField("DEPOTWBS"))
                {
                    if (item.foreign != null)
                    {
                        item.foreign.rowdisplay.Add("WAREHOUSENAME", "HQName");
                    }
                }
                if (item.IsField("MCODE"))
                {
                    item.title = "货物编码";
                    item.disabled = true;
                }
                if (item.IsField("Createdby"))
                {
                    item.title = "库管员";
                    item.disabled = true;
                    item.visible = true;
                }
                if (item.IsField("Creationdate"))
                {
                    item.title = "入库时间";
                    item.disabled = true;
                    item.visible = true;
                }
                if(item.IsField("FMODEL"))
                    item.disabled=true;
                if (item.IsField("DEPOTWBS"))
                    item.required = true;
            }
        }
        public static void InitInNoticeMaterials(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockInNoticeMaterials"))
            {
                data.title = "预收单明细";
                if (item.IsField("PARENTID")
                     || item.IsField("SourceCode")
                     || item.IsField("STATE")
                     || item.IsField("BATCHNO")
                     || item.IsField("BUMEN")
                     || item.IsField("WORKERID")
                     || item.IsField("IsDisable")
                     || item.IsField("code")
                     || item.IsField("Createdby")
                     || item.IsField("Creationdate")
                     || item.IsField("Reviewedby")
                     || item.IsField("Revieweddate")
                     || item.IsField("Submitedby")
                     || item.IsField("IsReviewed")
                     || item.IsField("IsSubmited")
                     || item.IsField("DEPOTWBS")
                     || item.IsField("HQNAME")
                     || item.IsField("Submiteddate"))
                    item.visible = false;
                if (item.IsField("MATERIALCODE"))
                    item.title = "货物名称";
                if (item.IsField("MCODE"))
                    item.title = "货物编码";
                if (item.IsField("FINISHNUM") || item.IsField("STAYNUM"))
                    item.disabled = true;
                //if (item.IsField("materialcode"))
                //{
                //    if (item.foreign != null)
                //    {
                //        //item.foreign.rowdisplay.Add("FMOBILE", "FMOBILE");//key是联系人表字段，value是客户表字段
                //        item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                //        item.foreign.rowdisplay.Add("CODE", "MCODE");
                //    }
                //}
                if (item.IsField("PARENTID"))
                {
                    item.foreign.foreignobject = typeof(StockInOrder).FullName;
                    item.foreign.foreignfiled = ("SourceID").ToUpper();
                    item.foreign.tablename = new StockInOrder().ToString();
                }
            }

        }

        public static void InitInSequence(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("InSequence"))
            {
                data.title = "入库序列码表";
                if (item.IsField("CODE")
                     || item.IsField("IsDisable")
                     || item.IsField("Createdby")
                     || item.IsField("Creationdate")
                     || item.IsField("Reviewedby")
                     || item.IsField("Revieweddate")
                     || item.IsField("IsReviewed")
                     || item.IsField("Submitedby")
                     || item.IsField("Submiteddate")
                     || item.IsField("IsSubmited")
                    )
                    item.visible = false;
                if (item.IsField("SEQUENCECODE"))
                    item.title = "序列号";
                
            }

        }

        public static void InitWareHouse(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("WareHouse"))
            {
                data.title = "货位信息";
                item.visible = false;
                //if (item.IsField("WHNAME") || item.IsField("MNAME") ||
                //item.IsField("model") || item.IsField("BATCHNO") || item.IsField("DCODE") || item.IsField("KYNUM") || item.IsField("NUM") || item.IsField("ZYNUM"))
                //    item.visible = true;
                //if (item.IsField("PARENTID")
                //     || item.IsField("ROWINDEX")
                //    )
                //    item.visible = false;
                if (item.IsField("CODE")) {
                    item.title = "货位";
                    item.index = 1;
                    item.visible = true;
                }
                if (item.IsField("WAREHOUSENAME"))
                {
                    item.title = "货区";
                    item.index = 0;
                    item.visible = true;
                }

               
            }
        }
        
        protected override void OnAdding(ControllerBase.SaveEvent item)
        {
            StockInOrder si = AddDefault(item);
            //新版本：根据客户ID，仓库ID，货物类别ID获取推荐货位,如为查询到结果，则放大范围到所有可用货位
            //20150215 隐藏推荐货位
            //foreach (StockInNoticeMaterials sinm in si.StayMaterials)
            //{

            //    //((IEntityBase)sinm).StateBase = EntityState.Select;
            //    string mid = sinm.MATERIALCODE;
            //    IDataAction ida = this.model.GetDataAction();
            //    string strSQL = GetRecommendHWSQL(int.Parse(mid));
            //    DataTable dt = ida.GetDataTable(strSQL);

            //    int wbsCount = dt.Rows.Count - 1;  //推荐货位个数
            //    if (dt.Rows.Count > 0)
            //    {
            //        sinm.DEPOTWBS = dt.Rows[0][1].ToString();
            //        sinm.HQName = dt.Rows[0][4].ToString();
            //    }
            //}
            isBatchManagement(item);
            setStateBase(si);
            ValidateSourceNum(si);
            ValidateItems(si);
            base.OnAdding(item);
        }

        //设置预收单明细的状态为select状态后，从预收单下推入库单时，避免重复新增一条纪录
        //先将DEPOTWBS置空再赋值，为了使save操作认为当前行的DEPOTWBS已被修改
        private void setStateBase(StockInOrder si)
        {
            foreach (StockInNoticeMaterials nm in si.StayMaterials)
            {
                string dep = nm.DEPOTWBS;
                nm.DEPOTWBS = "";
                string hqname = nm.HQName;
                nm.HQName = "";
                ((IEntityBase)nm).StateBase = EntityState.Select;
                nm.DEPOTWBS = dep;
                nm.HQName = hqname;
            }
        }

        protected override void OnEditing(ControllerBase.SaveEvent item)
        {
            isBatchManagement(item);
            StockInOrder si = AddDefault(item);
            setStateBase(si);
            ValidateSourceNum(si);
            ValidateItems(si);
            base.OnEditing(item);

        }
        protected override void OnEdited(EntityBase item)
        {
            base.OnEdited(item);
            if (item is BasicInfo)
            {
                setStatus((BasicInfo)item);
            }
        }

        protected override void Remove()
        {
            base.Remove();
            //置收货单及预收单状态
            setStatus(this.ActionItem);
        }

        protected override void OnSubmitData(BasicInfo info)
        {
            StockInOrder so = info as StockInOrder;
            if (so.IsSubmited == true)
            {
                throw new Exception("异常：单据已提交不能重复提交！");
            }
            so.Materials.DataAction = this.model.GetDataAction();
            so.Materials.GetData();
            if (so.Materials.Count == 0)
            {
                throw new Exception("单据无明细数据不能提交！");
            }
            
            base.OnSubmitData(info);
            setStatus(info);
            batchUpdateHWStatus(so); 
        }

        #endregion


        [ActionCommand(name = "导出", title = "导出", index = 10, icon = "icon-down", isselectrow = false, onclick = "emport4")]
        public void Emport()
        {
            //ExcelDRController er = new ExcelDRController();
            //er.bc = this;
        }

        //获得推荐货位
        protected string GetRecommendHWSQL(int mid)
        {
            int wid = 0, kid = 0, lid = 0;
            if (this.ActionItem["TOWHNO"] != null && !string.IsNullOrEmpty(this.ActionItem["TOWHNO"].ToString()))
                wid = int.Parse(this.ActionItem["TOWHNO"].ToString());
            if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                kid = int.Parse(this.ActionItem["CLIENTNO"].ToString());
            if (mid > 0)
            {
                IDataAction ida = this.model.GetDataAction();
                DataTable dt = ida.GetDataTable("select CLASSID from Acc_Bus_BusinessCommodity t1 where t1.ID = '" + mid + "'");
                if (dt.Rows.Count > 0)
                {
                    lid = int.Parse(dt.Rows[0][0].ToString());
                }
            }
            string strSQL = DepotwbsManage.GetDepotHWOrderByIdSQL(lid, wid, kid);
            return strSQL;

        }

        //判断预收单中待入库的商品是否需要批次管理，如果需要批次管理，则提醒用户必须录入批次号
        public void isBatchManagement(ControllerBase.SaveEvent item)
        {
            StockInOrder son = item.Item as StockInOrder;
            for (int i = 0; i < son.Materials.Count; i++)
            {
                var mcode = son.Materials[i].MCODE;
                var batchno = son.Materials[i].BATCHNO;
                EntityList<Materials> soo = new EntityList<Materials>(this.model.GetDataAction());
                soo.GetData("code='" + mcode + "'");
                if (soo.Count != 0)
                {
                    if (soo[0].BATCH == true && (batchno == null || batchno == ""))
                    {
                        throw new Exception("该商品的批次号不能为空。");
                    }
                }
            }
        }
        /// <summary>
        /// 货位id
        /// </summary>
        [WhereParameter]
        public string hwid { get; set; }
        [WhereParameter]
        public string hwzt { get; set; }
        public void sethw()
        {
            if (!string.IsNullOrEmpty(this.hwid))
            {
                int ttt = 0;
                if (!int.TryParse(hwid, out ttt))
                {
                    StockInOrder order = this.ActionItem as StockInOrder;
                    if (order != null)
                    {
                        if (order.Materials.Count > 0)
                            hwid = order.Materials[0].DEPOTWBS;
                    }
                }
            }
            bool b = false;
            if (!string.IsNullOrEmpty(this.hwzt))
                b = true;
            setHWStatus(hwid, b);
        }
        //更新货位状态：货位是否已满（可用）
        public void setHWStatus(string depotwbs, bool bl)
        {
            WareHouse wh = new WareHouse();
            string sql = "update " + wh.ToString() + " set STATUS='" + (bl?0:1).ToString() + "' where id = '" + depotwbs + "'";
            this.model.GetDataAction().Execute(sql);

        }

        //批量更新货位状态：货位是否已满（可用）
        public void batchUpdateHWStatus(BasicInfo item)
        {
            StockInOrder order = item as StockInOrder;

            WareHouse wh = new WareHouse();
            if (order.Materials.Count == 0)
            {
                order.Materials.DataAction = this.model.GetDataAction();
                order.Materials.GetData();
            }
            for (int i = 0; i < order.Materials.Count; i++)
            {
                setHWStatus(order.Materials[i].DEPOTWBS, order.Materials[i].STATUS);
            }

        }

        //设置预收单状态：0、未收货；1、部分收货；2、收货完成
        //设置入库单状态：0、未入库；1、部分入库；2、入库完成
        public void setStatus(EntityBase item)
        {
            StockInOrder order = item as StockInOrder;
            IDataAction action = this.model.GetDataAction();

            string state = "0";
            if (order.Materials.Count == 0)
            {
                order.Materials.DataAction = this.model.GetDataAction();
                order.Materials.GetData();
            }
            try
            {
                //从数据库查询入库情况
                string sqlSelect = "select t1.PARENTID," +
                                    "   sum(isnull(t1.NUM,0)) as NUM," +
                                    "   sum(isnull(t2.NUM,0)) as NUM1," +
                                    "   sum(isnull(t1.NUM,0)-isnull(t2.NUM,0)) as STAYNUM " +
                                    "from (" +
                                    "select PARENTID,ID,sum(NUM) as NUM " +
                                    "from Acc_WMS_InNoticeMaterials t1 " +
                                    "group by PARENTID,ID " +
                                    ") t1 " +
                                    "left join (" +
                                    "select SourceID,SourceRowID,sum(NUM) as NUM " +
                                    "from Acc_WMS_InOrderMaterials t1 " +
                                    "group by SourceID,SourceRowID " +
                                    ") t2 " +
                                    "on t1.PARENTID = t2.SourceID " +
                                    "and t1.ID = t2.SourceRowID " +
                                    "where t1.PARENTID  = '" + order.SourceID + "' " +
                                    "group by t1.PARENTID ";
                action.StartTransation();
                DataTable oldDataTable = action.GetDataTable(sqlSelect);
                foreach (DataRow oldRow in oldDataTable.Rows)
                {
                    if (Convert.ToInt16(oldRow["NUM"]) > 0)
                    {
                        if (Convert.ToInt16(oldRow["STAYNUM"]) > 0 && Convert.ToInt16(oldRow["STAYNUM"]) < Convert.ToInt16(oldRow["NUM"]))
                            state = "1";
                        else if (Convert.ToInt16(oldRow["STAYNUM"]) == 0)
                            state = "2";
                    }
                }

                if (order.Materials.Count>0 && (order.SourceCode == null ||order.SourceCode == ""))
                {
                        state = "2";
                }

                string sql = "update " + order.ToString() + " set STATE='" + state + "' where SourceID = '" + order.SourceID + "'";
                action.Execute(sql);
                sql = "update Acc_WMS_InNotice set STATE='" + state + "' where ID = '" + order.SourceID + "'";
                action.Execute(sql);
                action.Commit();
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                action.EndTransation();
            }

        }

        /// <summary>
        /// 添加默认值
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public StockInOrder AddDefault(ControllerBase.SaveEvent item)
        {
            StockInOrder si = item.Item as StockInOrder;
            EntityList<StockInNotice> list = new EntityList<StockInNotice>(this.model.GetDataAction());
            list.GetData(" ID='" + si.SourceID + "'");
            bool bl = true;//用于判断入库单明细中的货物编码是否在预收单明细中存在的标志位
            if (list.Count > 0)
            {
                list[0].Materials.DataAction = this.model.GetDataAction();
                list[0].Materials.GetData();
                si.SourceController = "Way.Bus.WMS.ST.Controllers.InOrder.ReceiveNoticeController";
                si.SourceID = list[0].ID;
                int hw=0;
                for (int j = 0; j < si.Materials.Count; j++)
                {
                    for (int i = 0; i < list[0].Materials.Count; i++)
                    {
                        //预收单的货物明细与入库单货物明细改为只按照Mcode进行比较 --1203 
                        //if (si.Materials[j].MCODE == list[0].Materials[i].MCODE && si.Materials[j].BATCHNO == list[0].Materials[i].BATCHNO ) 
                        if (si.Materials[j].MCODE == list[0].Materials[i].MCODE)
                        {
                            si.Materials[j].SourceRowID = list[0].Materials[i].ID;
                            si.Materials[j].SourceID = list[0].Materials[i].PARENTID;
                            si.Materials[j].SourceTable = list[0].Materials[i].ToString();
                            si.Materials[j].Createdby = this.user.ID;
                            si.Materials[j].Creationdate = DateTime.Now;
                            if (!string.IsNullOrEmpty(si.Materials[j].DEPOTWBS) && !int.TryParse(si.Materials[j].DEPOTWBS, out hw))
                                si.Materials[j].DEPOTWBS = WareHouse.GetDepotwesID(si.TOWHNO, si.Materials[j].DEPOTWBS, list[0].Materials.DataAction).ToString();
                            bl = false;
                        }
                    }
                    if (bl)
                    {
                        Materials a = si.Materials[j].GetForeignObject<Materials>(this.model.GetDataAction());
                        throw new Exception(" 商品名称:" + a.FNAME + "  商品编码：" + a.Code + " 入库单明细中的货物编码在预收单明细中不存在！");
                    }
                }
                

            }
            else { 
                //如果没有对应的预收单，不做任何加工，直接返回入库单信息
            }
            return si;
        }

        /// <summary>
        /// 验证源单数量是否正确
        /// </summary>
        /// <param name="stockinorder"></param>
        /// <param name="i"></param>
        public virtual void ValidateSourceNum(StockInOrder stockinorder)
        {
            //预收单的货物明细与入库单货物明细改为只按照Mcode进行比较 --1203 
            //var result = from o in stockinorder.Materials group o by new { o.SourceRowID, o.MATERIALCODE, o.BATCHNO } into g select new { g.Key, Totle = g.Sum(p => p.NUM), Items = g.ToList<StockInOrderMaterials>() };
            var result = from o in stockinorder.Materials group o by new { o.SourceRowID, o.MATERIALCODE } into g select new { g.Key, Totle = g.Sum(p => p.NUM), Items = g.ToList<StockInOrderMaterials>() };
            foreach (var group in result)
            {
                StockInOrderMaterials m = group.Items.Find(delegate(StockInOrderMaterials mm) { return ((IEntityBase)mm).StateBase == EntityState.Select; });
                if (m == null)
                    m = group.Items[0];

                if (group.Totle <= 0)
                {
                    throw new Exception("明细行数量错误");
                }
                if (m.SourceRowID > 0)
                {
                    Materials a = m.GetForeignObject<Materials>(this.model.GetDataAction());
                    //double snum = m.GetNum(m.SourceTable, m.SourceRowID, m.MATERIALCODE, m.BATCHNO);//获取总共下推的数量
                    //double bcnum = m.GetSourceNum(m.SourceTable, m.SourceRowID, m.MATERIALCODE, m.BATCHNO, stockinorder.ID);//获取已经完成的数量
                    double snum = m.GetNum(m.SourceTable, m.SourceRowID, m.MATERIALCODE);//获取总共下推的数量
                    double bcnum = m.GetSourceNum(m.SourceTable, m.SourceRowID, m.MATERIALCODE, stockinorder.ID);//获取已经完成的数量
                    //m.NUM当前页面数量的总和（相同行id）
                    if (group.Totle > snum)
                        throw new Exception("序号:" + m.RowIndex + " 商品名称:" + a.FNAME + "  商品编码：" + a.Code + " 数量超过源单数量");
                    if (group.Totle > snum - bcnum)
                        throw new Exception("序号:" + m.RowIndex + " 商品名称:" + a.FNAME + "  商品编码：" + a.Code + " 数量超过源单数量.");

                }
            }

        }

        /// <summary>
        /// 验证产品编码和货位编码
        /// </summary>
        /// <param name="stockinorder"></param>
        /// <param name="i"></param>
        public virtual void ValidateItems(StockInOrder stockinorder)
        {
            foreach (StockInOrderMaterials item in stockinorder.Materials)
            {
                if (string.IsNullOrEmpty(item.MCODE))
                    throw new Exception("产品编码不能为空！");
                if(string.IsNullOrEmpty(item.DEPOTWBS))
                    throw new Exception("货位不能为空！");
            }
        }
       
    }
    
}
